package com.qf.mybatis.test;

import com.qf.mybatis.entity.User;
import com.qf.mybatis.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 郑大仙丶
 * @version 1.0
 * @date 2021/3/16 14:48
 * 测试MyBatis的缓存
 */
public class Demo13 {

    @Test
    public void oneLevelCache() throws IOException {
        // inputStream
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        // builder
        // factory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

        // sqlSession1
        SqlSession sqlSession1 = factory.openSession();

        UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);

        // 第一次查询
        User user1 = userMapper1.findById(1);
        // 第一次查询，现查询缓存，缓存没有，查询数据库，将查询到的数据存储到缓存

        // 第二次查询
        User user2 = userMapper1.findById(1);
        // 第二次查询，先查询缓存，缓存有！

        System.out.println(111);


    }

    @Test
    public void twoLevelCache() throws IOException {
        // inputStream
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        // builder
        // factory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

        // sqlSession1
        SqlSession sqlSession1 = factory.openSession();
        SqlSession sqlSession2 = factory.openSession();

        // 获取Mapper对象
        UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
        UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);

        // 查询数据
        User user1 = mapper1.findById(2);
        sqlSession1.commit();
        sqlSession1.close();


        User user2 = mapper2.findById(2);
        sqlSession2.commit();
        sqlSession2.close();
        // ....
        System.out.println(111);

    }

}
